#! /usr/bin/env python3

import argparse
import shutil
import subprocess
import sys
import os

from oclintscripts import cmake
from oclintscripts import environment
from oclintscripts import path
from oclintscripts import process

arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('task_name', choices=['checkout', 'co', 'update', 'up', 'build'])
arg_parser.add_argument('-clean', '--clean', action="store_true")
arg_parser.add_argument('-j', type=int, default=0)
args = arg_parser.parse_args()

def clean_module():
    build_path = path.build.googletest_build_dir
    path.rm_f(build_path)

def build_command():
    gtest_dir = path.source.googletest_dir
    cmd_build = cmake.builder(gtest_dir)
    if environment.is_mingw32():
        cmd_build.append('gtest_disable_pthreads:BOOL', 'ON')
    if environment.is_darwin():
        cmd_build.append('CMAKE_CXX_FLAGS', '-std=c++11 -stdlib=libc++ ${CMAKE_CXX_FLAGS}', True)
    return cmd_build.str()

def build_module(j):
    build_path = path.build.googletest_build_dir

    command = build_command()

    current_dir = os.getcwd()
    path.mkdir_p(build_path)
    path.cd(build_path)
    process.call(command)
    process.make(j)
    path.cd(current_dir)

def checkout_googletest():
    if path.is_dir(path.source.googletest_dir):
        sys.exit('GoogleTest folder exists!')
    current_dir = os.getcwd()
    path.cd(path.root_dir)
    process.call('git clone ' + path.url.googletest + ' googletest')
    path.cd(current_dir)

def update_googletest():
    if not path.is_dir(path.source.googletest_dir):
        sys.exit('GoogleTest folder does not exist!')
    current_dir = os.getcwd()
    path.cd(path.source.googletest_dir)
    process.call('git pull')
    path.cd(current_dir)

if args.task_name == 'checkout' or args.task_name == 'co':
    checkout_googletest()

if args.task_name == 'update' or args.task_name == 'up':
    update_googletest()

if args.task_name == 'build':
    if args.clean:
        clean_module()
    build_module(args.j)
